<?php


namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\Request;
use App\Services\WarrantyDeleteService;

class WarrantyDeleteController extends Controller
{
    private $warrantyDeleteService;

    public function __construct(WarrantyDeleteService $warrantyDeleteService)
    {
        $this->warrantyDeleteService = $warrantyDeleteService;
    }

    public function index(Request $request)
    {
        $list = $this->warrantyDeleteService->getList($request);
        $page = [
            'page_name' => 'warranty',
            'title' => '删除质保列表',
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEWARRANTY'),
                    'url' => '/admin/warranty'
                ]
            ],
        ];

        if (session('admin.user_type') == 1) {
            $distributions = Admin::where('status', 1)->where("user_type", 2)->get();
        }

        return view('admin.warranty_delete.index',
                [
                    'data'  => $list ?? [],
                    'page'  => $page,
                    'user_type' => session('admin.user_type'),
                    'distributions' => $distributions ?? [],
                ]
            );
    }

    public function add(Request $request)
    {
        $user_type = session('admin.user_type');
        if ($user_type != 2) {
            return abort(404);
        }
        $page = [
            'page_name' => 'warranty',
            'title' => '增加删除质保',
            'breadcrumb' => [
                [
                    'text' => ts('MANAGEWARRANTY'),
                    'url' => '/admin/warranty'
                ]
            ],
        ];

        return view('admin.warranty_delete.add',
            [
                'data'  => [],
                'page'  => $page
            ]);
    }

    public function store(Request $request)
    {
        try {
            $this->warrantyDeleteService->add($request);
        } catch (\Exception $exception) {
            return response([
                'code' => 1000,
                'msg'  => $exception->getMessage() ?? '申请失败'
            ]);
        }

        return response()->json([
            'code'  => 0
        ]);
    }

    /**
     * 删除
     *
     * @param int $id
     * @return array|JsonResponse
     */
    public function delete(int $id)
    {
        try {
            $this->warrantyDeleteService->delete($id);
        } catch (\Exception $exception) {
            return fs404($exception->getMessage());
        }

        return fs200('deleteSuccess');
    }
}